#include <string.h>
#include <esp_wifi.h>

#include <esp_log.h>
static const char *TAG = "bsp.key";

#include "button_gpio.h"
#include "iot_button.h"

#define BOOT_BUTTON_NUM     0
#define BUTTON_ACTIVE_LEVEL 0

static void button_event_cb(void *arg, void *data)
{
    button_handle_t btn_handle = (button_handle_t)arg;
    iot_button_print_event(btn_handle);

    button_event_t event = iot_button_get_event(btn_handle);

    if (event == BUTTON_LONG_PRESS_START)
    {
        ESP_LOGI(TAG, "esp_wifi_restore");

        esp_wifi_restore();
    }
}

void bsp_keyInit()
{
    button_config_t btn_cfg = {0};
    button_gpio_config_t gpio_cfg = {
        .gpio_num = BOOT_BUTTON_NUM,
        .active_level = BUTTON_ACTIVE_LEVEL,
        .enable_power_save = true,
    };

    button_handle_t btn;
    esp_err_t ret = iot_button_new_gpio_device(&btn_cfg, &gpio_cfg, &btn);
    assert(ret == ESP_OK);

    ret = iot_button_register_cb(btn, BUTTON_PRESS_DOWN, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_PRESS_UP, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_PRESS_REPEAT, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_PRESS_REPEAT_DONE, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_SINGLE_CLICK, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_DOUBLE_CLICK, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_LONG_PRESS_START, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_LONG_PRESS_HOLD, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_LONG_PRESS_UP, NULL, button_event_cb, NULL);
    ret |= iot_button_register_cb(btn, BUTTON_PRESS_END, NULL, button_event_cb, NULL);

    ESP_ERROR_CHECK(ret);
}